import json

from django.shortcuts import render
import time, datetime, oss2
# 导入token验证函数
from common.token_dec import *
# 导入正则模块
from re import compile
# 导入QQ邮箱验证码
from common.user.email_code import *
# 导入模型类
from .models import *
# 导入用户类
from users.models import *
# 导入加密密码函数
from common.user.encrypt import pass_encrypt
# 导入生成手机验证码函数
from common.user.code import *
# 处理地址管理函数
from common.userInfo.address import *
# 导入响应数据函数
from common.respond.res import res


# Create your views here.


# 获取登录用户信息
@token_dec
def get_user_info(request):
    # 获取当前token用户对象
    user = request.myuser
    # 将明文密码清空
    user['passStr'] = ''
    stamp = user['create_time'].strftime("%Y-%m-%d %H:%M:%S")
    # 转换时间戳
    user['time_stamp'] = stamp
    # 未获取数据
    if not user:
        return res(400, "获取失败！", {"err": "用户获取失败，请稍后再试！"})
    # 获取成功
    return res(200, "获取成功！", {"user": user})


@token_dec
# 获取订单中心数据
def get_order_cen(request):
    order_list = list(OrderCenter.objects.all().values())
    # 获取全部数据
    return res(200, "获取成功！", {"orderList": order_list})


@token_dec
# 获取我的服务数据
def get_my_server(request):
    # 判断是否异步登录
    as_data = async_log(request.myuser['userId'], request.META.get("HTTP_AUTHORIZATION"))
    if as_data:
        return res(404, "登录失效！", {'err': "您的账号在其他地方登录,您已经被强制下线！"})
    my_server = list(MyService.objects.all().values())
    # 获取全部数据
    return res(200, "获取成功！", {"severList": my_server})


@token_dec
# 更改用户信息
def user_edit(request):
    # 获取当前token用户id
    user_id = request.myuser['userId']
    # 获取修改的数据
    user_data = eval(request.body.decode())
    # 获取当前用户id信息
    user_info = Users.objects.get(userId=user_id)
    user_info.userImg = user_data['userImg']
    user_info.nickName = user_data['nickName']
    user_info.save()  # 保存修改
    return res(200, "修改成功！", {"ret": "设置成功！"})


# 创建一个put_object_oss方法
def put_object_oss(ObjectName, LocalFile):
    # oss配置信息
    auth = oss2.Auth('LTAI5tAXfizWLidPCAWaZGcW', 'hEY2ZSu0IyC62sybsBZjMqv7gJnjFq')
    # Bucket名称。
    bucket = oss2.Bucket(auth, 'https://oss-cn-chengdu.aliyuncs.com', 'chenjdd')
    # 上传文件名，本地文件路径
    bucket.put_object(ObjectName, LocalFile)
    # 返回的网址
    return f"https://chenjdd.oss-cn-chengdu.aliyuncs.com/{ObjectName}"


# 上传图片至阿里云oss
def uploads(request):
    # 通过异常处理来处理上传图片
    try:
        # 获取前端的图片对象
        image_object = request.FILES.get('file')
        # 图片名和后缀名分开成数组（获取上传文件的后缀名）
        image_arr = image_object.name.rsplit('.')
        # 重新命名的名字（我这里使用time，防止重复的可以选择uuid）
        image_name = image_arr[0] + "-" + str(int(time.time() * 1000)) + "." + image_arr[1]
        # 获取当前的日期
        current_date = datetime.datetime.now().strftime('%Y-%m-%d')
        # 若输入的目录不存在, OSS将自动创建对应的文件目录并将文件上传到该目录中。
        key = f"files/{current_date}/{image_name}"
        # read()获取image_object的bytes字节串；
        image_object_bytes = image_object.read()
        # 传给put_object_oss方法
        imageSrc = put_object_oss(ObjectName=key, LocalFile=image_object_bytes)
    # 发生异常
    except Exception as e:
        print(e)
        return res(400, "上传失败！", {"error": "上传失败，请稍后在试！"})
    else:
        return res(200, "上传成功！", {"imageUrl": imageSrc})


# 发送QQ邮箱验证码
def send_email_code(request):
    # 获取邮箱
    qq_email = request.GET.get("email")
    # 验证码邮箱
    if compile(r'^[\w]{1,19}@(qq).(com)$').match(qq_email):
        if Users.objects.filter(email=qq_email).exists():
            return res(400, "发送失败！", {'err': "邮箱已被绑定！"})
        # 发送验证码
        data = sendemail(qq_email)
        if data:
            # 发送成功
            return res(200, "发送成功！", {'time': int(time.time()), "phone": qq_email})
    elif not qq_email:
        # 邮箱为空
        return res(400, "发送失败！", {'err': "手机号不能为空！"})
    elif not compile(r'^[\w]{1,19}@(qq).(com)$').match(qq_email):
        # 邮箱号格式错误
        return res(400, "发送失败！", {'err': "邮箱格式错误！"})


@token_dec
# 绑定QQ邮箱
def bing_email(request):
    # 获取当前token用户id
    user_id = request.myuser['userId']
    # 获取邮箱绑定的参数
    userinfo = eval(request.body.decode())
    qq_email = userinfo['email']
    code_num = userinfo['code']
    # 判断邮箱是否被绑定
    if Users.objects.filter(email=userinfo['email']).exists():
        return res(400, "绑定失败！", {'err': "邮箱已被其他用户绑定！"})
    # 取出当前邮箱验证码表
    code_data = email_code.objects.get(email=qq_email)
    # 判断是否过期
    if int(time.time()) > int(code_data.time):
        return res(400, "验证失败！", {'err': "验证码已过期，请重新发送！"})
    else:
        # 判断验证码是否正确
        if code_num == code_data.code:
            # 获取当前用户id信息
            user_info = Users.objects.get(userId=user_id)
            user_info.email = userinfo['email']
            user_info.save()  # 保存修改
            return res(200, "绑定成功！", {"email": userinfo['email'], "phone": user_info.phone})
        else:
            return res(400, "绑定失败！", {'user': "验证码错误，请重新输入！"})


# 发送修改密码验证码
def send_pwd_code(request):
    # 验证码类型
    type_id = "修改密码验证码"
    # 手机号
    phone = request.GET.get("phone")
    # 验证手机号
    if compile(r'^1[34578]\d{9}$').match(phone):
        # 调用发送验证码方法
        data = log_codes(phone, type_id)
        print(data)
        # 发送成功
        return res(200, "发送成功！", {"phone": phone, 'time': int(time.time())})
    elif not phone:
        # 手机号为空
        return res(400, "发送失败！", {'err': "手机号不能为空！", 'time': int(time.time())})
    elif not compile(r'^1[34578]\d{9}$').match(phone):
        # 手机号格式错误
        return res(400, "发送失败！", {'err': "手机号格式错误！", 'time': int(time.time())})


@token_dec
# 更改用户密码
def update_pwd(request):
    # 获取当前token用户id
    user_id = request.myuser['userId']
    user = Users.objects.get(userId=user_id)
    # 获取修改密码的参数
    user_data = eval(request.body.decode())
    # 判断旧密码是否相同
    if user.passStr != user_data['old_pwd']:
        return res(400, "修改失败！", {'err': "原密码错误！", "time": int(time.time())})
    # 判断新密码和旧密码是否一样
    if user_data['old_pwd'] == user_data['new_pwd']:
        return res(400, "修改失败！", {'err': "新密码和旧密码不能相同！！", "time": int(time.time())})
    # 取出当前邮箱验证码表
    code_data = Code.objects.get(phone=user.phone)
    # 判断是否过期
    if int(time.time()) > int(code_data.pwd_time):
        return res(400, "验证失败！", {'err': "验证码已过期，请重新发送！", "time": int(time.time())})
    # 验证验证码是否正确
    if user_data['code'] != code_data.pwd_code:
        return res(400, "验证失败！", {'user': "验证码错误，请重新输入！"})
    # 将密码加密
    user.passStr = user_data['new_pwd']
    user.password = pass_encrypt(user_data['new_pwd'])
    user.save()  # 保存
    return res(200, "修改成功！",
               {"phone": user.phone, "new_pwd": pass_encrypt(user_data['new_pwd']), "time": int(time.time())})


@token_dec
# 添加收货地址
def add_address(request):
    # 获取当前token用户id
    user_id = request.myuser['userId']
    # 获取到添加的地址参数
    user_data = json.loads(request.body.decode())
    # 先查出当前用户是否添加了5条收货地址
    address_num = Address.objects.filter(uid=user_id).count()
    if address_num >= 5:
        return res(400, "添加失败！", {'err': "收货地址已达上限，每位用户最多5个收货地址！", 'time': int(time.time())})
    # 地址id
    add_id = int(random.random() * 100000)
    # 是否默认地址
    if user_data['isDefault']:
        is_default = "true"
        # 当前地址设置默认的话，其他地址就取消默认
        user_address = Address.objects.filter(uid=user_id)
        for i in user_address:
            i.isDefault = "false"
            i.save()  # 保存
    else:
        is_default = "false"
    # 添加收货地址
    Address(uid=user_id, address_id=add_id, name=user_data['name'], tel=user_data['tel'],
            province=user_data['province'], city=user_data['city'], county=user_data['county'],
            areaCode=user_data['areaCode'], country=user_data['country'],
            addressDetail=user_data['addressDetail'], isDefault=is_default).save()

    return res(200, "添加成功！", {'info': user_data, 'time': int(time.time())})


@token_dec
# 获取收货地址
def get_address(request):
    # 获取当前token用户id
    user_id = request.myuser['userId']
    # 通过用户id查询当前的用户收货地址
    address = list(Address.objects.filter(uid=user_id).values())
    return res(200, "获取成功！", {"info": address, 'time': int(time.time())})


@token_dec
# 修改默认收货地址
def set_default_address(request):
    # 获取当前token用户id
    user_id = request.myuser['userId']
    # 获取到添加的地址参数
    user_data = json.loads(request.body.decode())
    # 现将全部地址取消默认
    user_address = Address.objects.filter(uid=user_id)
    for i in user_address:
        i.isDefault = "false"
        i.save()  # 保存
    # 在将现在的地址设置默认
    address = Address.objects.get(uid=user_id, id=user_data['id'], address_id=user_data['address_id'])
    address.isDefault = 'true'
    address.save()  # 保存
    return res(200, "设置成功！", {'time': int(time.time())})


@token_dec
# 删除地址
def delete_address(request):
    # 获取当前token用户id
    user_id = request.myuser['userId']
    # 获取到添加的地址参数
    user_data = json.loads(request.body.decode())
    # 删除地址
    Address.objects.get(uid=user_id, address_id=user_data['address_id']).delete()

    return res(200, "删除成功！", {'time': int(time.time())})



